<?php

$res = file_get_contents('php://input');
$data = json_decode($res, true);
$key = $data['key'];
$title = $data['title'];
$description = $data['description'];

$status = false;

if(!is_dir($key)) {
// logo图片
mkdir($key,0777,true);

$icon = preg_replace("/^data:image\/\w+;base64,/", "", $data['icon']);
$icon_f = fopen('./'.$key.'/icon.png', "wb");
fwrite($icon_f, base64_decode($icon) );
fclose($icon_f);

// 压缩文件
$lastVersion = $data['version'][0]['version'];
$lastVersionFile = $data['version'][0]['file'];
$Version_f = fopen('./'.$key.'/'.$key.'-v'.$lastVersion.'.zip', "wb");

fwrite($Version_f, base64_decode($lastVersionFile) );
fclose($Version_f);
$config = [
    'index' => 'index.html',
    'minWidth' => 1280,
    'minHeight' => 800,
    'title' => $key,
    'key' => $key,
    'name' => $title,
    'localVersion' => $lastVersion,
    'icon' => 'icon.png'
];

$configPath = fopen('./'.$key.'/config.json', "wb");
fwrite($configPath, json_encode($config));
fclose($configPath);


// $index_string = file_get_contents('./'.$key.'/index.json');
// $index = json_decode($index_string, true);

$count = count($data['version']);

$index_file = array();

for($i=0;$i<$count;$i++){
    array_push($index_file,array(
        "date"=>$data['version'][$i]['date'],
        "debug"=>$data['version'][$i]['debug'],
        "update"=>$data['version'][$i]['update'],
        "FileName"=>$key.'-v'.$lastVersion.'.zip',
        "version"=>$data['version'][$i]['version']
    ));
}

$index_Path = fopen('./'.$key.'/index.json', "wb");
fwrite($index_Path, json_encode($index_file));
fclose($index_Path);


$index_by_config = [
    "key"=>$key,
    "path"=>"/".$key."/index.json",
    "title"=>$title,
    "description"=>$description,
    "icon"=>"/".$key."/icon.png",
    "lastVersion"=>$lastVersion,
];
$index_by_string = file_get_contents('./index.json');
$index_by = json_decode($index_by_string, true);

array_push($index_by, $index_by_config);
$index_Path_Save = fopen('./index.json', "wb");
fwrite($index_Path_Save, json_encode($index_by));
fclose($index_Path_Save);

$status = true;
    // echo true
} else {
    header("HTTP/1.1 500 Internal Server Error"); 
    // echo '已经存在APP'
};

echo $status || '已经存在APP';
?>